package day_2023_4_to_7;

import java.util.Arrays;

/**
 * @author haomin
 * @date 2023/04/20 20:56
 **/
public class Day4_20_Num1187 {
    class Solution {
        public int makeArrayIncreasing(int[] arr1, int[] arr2) {
            int n = arr1.length, m = arr2.length;
            final int INF = 0x3f3f3f3f;
            int[][] dp = new int[n + 1][m + 1];
            Arrays.sort(arr2);

            dp[1][0] = 0;
            Arrays.fill(dp[1], 1, m + 1, 1);
            for (int i = 2; i <= n; i++) {
                // 不换
                dp[i][0] = INF;
                if (arr1[i - 2] < arr1[i - 1]) dp[i][0] = Math.min(dp[i][0], dp[i - 1][0]);
                for (int j = 1; j <= m && arr2[j - 1] < arr1[i - 1]; j++) dp[i][0] = Math.min(dp[i][0], dp[i - 1][j]);

                // 换
                for (int j = 1; j <= m; j++) {
                    dp[i][j] = INF;
                    if (arr1[i - 2] < arr2[j - 1]) dp[i][j] = Math.min(dp[i][j], dp[i - 1][0] + 1);
                    if (j > 1) {
                        dp[i][j] = Math.min(dp[i][j], dp[i][j - 1]);
                        if (arr2[j - 2] < arr2[j - 1]) dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1] + 1);
                    }
                }
            }

            int ans = INF;
            for (int j = 0; j <= m; j++) ans = Math.min(ans, dp[n][j]);
            if (ans >= INF) ans = -1;
            return ans;
        }
    }
}